package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.qcloud.qcloudcos.CosConstants;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.AnalysisVisualCatalogDTO;
import com.hunttown.mes.rpc.domain.TransportNewsDTO;
import com.hunttown.mes.rpc.domain.TransportUploadFilesDTO;
import com.hunttown.mes.rpc.domain.query.TransportNewsDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportUploadFilesDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 文章管理
 * @author: wangjunfu
 * @date: 2020-05-26 01:40:42
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/article")
public class NewsController {

    private final static Logger logger = LoggerFactory.getLogger(NewsController.class);

    private final TransportNewsManageService newsService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportUploadFilesManageService uploadFilesService;
    private final AnalysisCatalogManageService catalogService;
    private final TransportOperateLogManageService logService;
    private final AnalysisWebsiteParamManageService websiteService;

    @Autowired
    public NewsController(TransportNewsManageService newsService, AnalysisManageManageService manageService, ModelService modelService, TransportUploadFilesManageService uploadFilesService, AnalysisCatalogManageService catalogService, TransportOperateLogManageService logService, AnalysisWebsiteParamManageService websiteService) {
        this.newsService = newsService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.uploadFilesService = uploadFilesService;
        this.catalogService = catalogService;
        this.logService = logService;
        this.websiteService = websiteService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportNewsDTOQuery dtoQuery) {

        if ((dtoQuery.getCatalogId() == null || dtoQuery.getCatalogId() <= 0) && StringUtils.isBlank(dtoQuery.getCatalogNameEn())) {
            throw new RuntimeException("查询请求失败，请重新打开页面！");
        }

        //文章类别
        AnalysisVisualCatalogDTO catalogDTO = null;

        //通过ID获取
        if (dtoQuery.getCatalogId() != null && dtoQuery.getCatalogId() > 0) {
            catalogDTO = catalogService.getFromCacheId(dtoQuery.getCatalogId());
        }

        //通过英文代码获取
        if (catalogDTO == null && StringUtils.isNotBlank(dtoQuery.getCatalogNameEn())) {
            catalogDTO = catalogService.getByCateEnName(dtoQuery.getCatalogNameEn());
        }

        //分类信息是否存在
        if (catalogDTO == null) {
            if (StringUtils.isNotBlank(dtoQuery.getCatalogNameEn())) {
                throw new RuntimeException("您要查询的类目【" + dtoQuery.getCatalogNameEn() + "】不存在，请先添加");
            } else {
                throw new RuntimeException("您要查询的类目不存在，请先添加");
            }
        } else {
            dtoQuery.setCatalogId(catalogDTO.getId());
        }

        //“记事本”：只能查看和编辑自己的内容
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        if (catalogDTO.getCatalogNameEn().toLowerCase().equals("jishiben")) {
            dtoQuery.setAdminId(curr_obj.getId());
        }

        //当前是否“会议纪要”栏目
        int isHuiyijiyao = 0;

        //“会议纪要”：只能编辑自己的内容，但可以查看所有的内容
        if (catalogDTO.getCatalogNameEn().toLowerCase().equals("huiyijiyao")) {
            isHuiyijiyao = 1;
        }

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportNewsDTO> dataPage = newsService.getForPage(dtoQuery);

        for (TransportNewsDTO item : dataPage.getItems()) {
            item.setCatalogName(modelService.getCatalogName(item.getCatalogId()));
            item.setAdminName(modelService.getManageName(item.getAdminId()));

            item.setCanExec(1);
            if (isHuiyijiyao == 1 && !Objects.equals(item.getAdminId(), curr_obj.getId())) {
                //会议纪要，如果不是自己的则不能编辑
                item.setCanExec(0);
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //region 标题显示
        model.addAttribute("showtitle", catalogDTO.getCatalogName());
        model.addAttribute("cate_en", catalogDTO.getCatalogNameEn().toLowerCase());
        //endregion

        //region 页面按钮权限
        String[] menus = {"W-G-HYJY-SC"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "basic/article/index";
    }

    /**
     * 详情
     *
     * @param model model模型
     * @param id    详情ID
     * @return vm
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(HttpServletRequest request, Model model, Integer id) throws Exception {
        if (id == null || id <= 0) {
            throw new RuntimeException("未找到任务信息！");
        }

        //当前用户
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        TransportNewsDTO obj = newsService.getById(id);

        //region 处理解密（加密文件只能本人查看）
        if (obj.getIsSecret() == 1) {
            if (!Objects.equals(obj.getAdminId(), curr_obj.getId())) {
                throw new RuntimeException("你没有权限查看当前内容！");
            }
            obj.setNewsContent(DesUtils.decrypt(obj.getNewsContent()));
        }
        //endregion

        obj.setCatalogName(modelService.getCatalogName(obj.getCatalogId()));
        obj.setAdminName(modelService.getManageName(obj.getAdminId()));

        //region 获取已上传文件
        modelService.getUploadPage(model, obj.getIsUpload());
        //endregion

        model.addAttribute("Obj", obj);

        //更新浏览记录
        TransportNewsDTO update = new TransportNewsDTO();
        update.setHits(obj.getHits() + 1);
        update.setId(obj.getId());
        newsService.updateInfoById(update);

        //版权信息
        model.addAttribute("copyright", websiteService.getWebsiteCopyrightFromCache(request, pin));

        return "basic/article/detail";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return vm
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id, Integer catalogId) throws Exception {
        id = (id == null ? 0 : id);

        if (catalogId == null || catalogId <= 0) {
            throw new RuntimeException("编辑请求失败，请重新操作！");
        }

        //当前用户
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        //文章类别
        AnalysisVisualCatalogDTO catalogDTO = catalogService.getFromCacheId(catalogId);
        if (catalogDTO == null) {
            throw new RuntimeException("未获取到类目，请重新操作！");
        }

        TransportNewsDTO obj;
        if (id > 0) {
            obj = newsService.getById(id);

            //region 处理加密（加密文件只能本人操作）
            if (obj.getIsSecret() == 1) {
                if (!Objects.equals(obj.getAdminId(), curr_obj.getId())) {
                    throw new RuntimeException("你没有权限操作当前内容！");
                }
                obj.setNewsContent(DesUtils.decrypt(obj.getNewsContent()));
            }
            //endregion

            //region 获取已上传文件
            modelService.getUploadPage(model, obj.getIsUpload());
            model.addAttribute("mainPicId", obj.getPicId()); //主图
            //endregion

        } else {
            obj = new TransportNewsDTO();
            obj.setId(0);
            obj.setCatalogId(catalogId);
            obj.setNewsType(1);
            obj.setTitleColor("#ffffff");
            obj.setPicId(0);
            obj.setHits(0);
            obj.setSort(0);
            obj.setAuthor("本站");
            obj.setOrigin("原创");

            //region 记事本默认选择加密
            if (catalogDTO.getCatalogNameEn().toLowerCase().equals("jishiben")) {
                obj.setIsSecret(1);
            }
            //endregion

            //region 会议纪要模板
            if (catalogDTO.getCatalogNameEn().toLowerCase().equals("huiyijiyao")) {
                obj.setFullTitle(String.format("%s（xxx部）关于xxx的会议纪要", DateConvertUtils.dateToChineseStr(new Date())));

                String content = "<p><strong>会议时间</strong>：</p>" +
                        "" +
                        "<p><strong>会议地点</strong>：</p>" +
                        "" +
                        "<p><strong>主&ensp;持&ensp;人</strong>：</p>" +
                        "" +
                        "<p><strong>参会人员</strong>：</p>" +
                        "" +
                        "<p><strong>记&ensp;录&ensp;人</strong>：</p>" +
                        "" +
                        "<p><strong>会议主题</strong>：</p>" +
                        "" +
                        "<p><strong>会议内容</strong>：</p>" +
                        "" +
                        "<p>1、</p>" +
                        "" +
                        "<p>2、</p>" +
                        "" +
                        "<p>3、</p>";
                obj.setNewsContent(content);
            }
            //endregion

        }
        model.addAttribute("Obj", obj);

        //文章类别
        modelService.getCatalogPage(model, 2);
        modelService.getCatalogPage(model, 3, "brandCateList");

        //region 文件上传使用
        model.addAttribute("uploadTableName", "transport_news");
        model.addAttribute("uploadRecordId", obj.getId());

        String catalog = modelService.getCatalogNameEn(catalogId);
        String uploadPrefix = CosConstants.getStorageFolder(catalog);
        model.addAttribute("uploadPrefix", uploadPrefix);
        //endregion

        //标题显示
        model.addAttribute("showtitle", catalogDTO.getCatalogName());

        return "basic/article/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return string
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportNewsDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //不给副标题强行赋值了
            //if (StringUtils.isBlank(objDTO.getShortTitle())) {
            //    objDTO.setShortTitle(objDTO.getFullTitle());
            //}

            if (objDTO.getIsBold() == null) {
                objDTO.setIsBold(0);
            }
            if (objDTO.getIsItalic() == null) {
                objDTO.setIsItalic(0);
            }
            if (objDTO.getIsRecommend() == null) {
                objDTO.setIsRecommend(0);
            }
            if (objDTO.getIsRoll() == null) {
                objDTO.setIsRoll(0);
            }
            if (objDTO.getIsStrip() == null) {
                objDTO.setIsStrip(0);
            }
            if (objDTO.getIsHot() == null) {
                objDTO.setIsHot(0);
            }
            if (objDTO.getIsSlide() == null) {
                objDTO.setIsSlide(0);
            }
            if (objDTO.getIsTop() == null) {
                objDTO.setIsTop(0);
            }
            if (objDTO.getIsRecomment() == null) {
                objDTO.setIsRecomment(0);
            }
            if (objDTO.getIsLinks() == null) {
                objDTO.setIsLinks(0);
            }
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }
            if (objDTO.getIsSecret() == null) {
                objDTO.setIsSecret(0);
            }
            if (objDTO.getSort() == null) {
                objDTO.setSort(0);
            }

            //前端显示发布日期
            if (objDTO.getUpdateTimeDateSr() != null) {
                objDTO.setUpdateTime(DateConvertUtils.strToDate(objDTO.getUpdateTimeDateSr()));
            } else {
                objDTO.setUpdateTime(new Date());
            }

            //处理上传ID
            objDTO.setIsUpload(FormatUtils.formatCommas(objDTO.getIsUpload()));

            //每次修改后状态都要设置为：草稿，重新审核
            objDTO.setStatus(0);

            //region //文章主图
            //1. 优先级：用户复制的URL
            //2. 优先级：用户手动选取
            //3. 优先级：取图片中的第一张图
            boolean isSetPic = false; //标志是否已经设置了主图

            if (StringUtils.isNotBlank(objDTO.getPicUrl())) {
                //获取到的url和数据库中的不一致，则说明用户主动复制了互联网中的地址，则以用户主动复制为主
                if (objDTO.getId() == null || objDTO.getId() <= 0) {
                    isSetPic = true;
                } else {
                    TransportNewsDTO oldDTO = newsService.getFromCacheId(objDTO.getId());
                    if (!oldDTO.getPicUrl().equals(objDTO.getPicUrl())) {
                        objDTO.setPicId(0); //用户自己复制了地址，就不需要指定PICID了
                    }
                    isSetPic = true;
                }
            }

            if (!isSetPic && (objDTO.getPicId() == null || objDTO.getPicId() <= 0)) {
                if (StringUtils.isNotBlank(objDTO.getIsUpload())) {
                    String fileid = objDTO.getIsUpload().split(",")[0];
                    if (StringUtils.isNotBlank(fileid)) {
                        objDTO.setPicId(Integer.valueOf(fileid));
                    }
                }
            }

            if (!isSetPic && objDTO.getPicId() > 0) {
                TransportUploadFilesDTO fileDTO = uploadFilesService.getById(objDTO.getPicId());
                if (fileDTO != null) {
                    objDTO.setPicUrl(fileDTO.getWebUrl());
                }
            }
            //endregion

            //处理加密
            if (objDTO.getIsSecret() == 1) {
                objDTO.setNewsContent(DesUtils.encrypt(objDTO.getNewsContent()));
            }

            //判断内容长度
            if (objDTO.getNewsContent().length() > 65000) {
                map = OperateCode.CompositionResult(map, -10, "你保存的内容过长，请分开保存！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);

                //默认值
                objDTO.setStars(5);
                objDTO.setHitsForDay(0);
                objDTO.setHitsForMonth(0);
                objDTO.setHitsForWeek(0);

                objDTO.setVerifyId(0);
                objDTO.setVerifyDate(DateConvertUtils.strToDate("1990-01-01"));

                objDTO = newsService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //region 更新文件上传表中的recordId

                //1.直接更新
                if (StringUtils.isNotBlank(objDTO.getIsUpload())) {
                    TransportUploadFilesDTOQuery uploadFilesDTO = new TransportUploadFilesDTOQuery();
                    uploadFilesDTO.setRecordId(objDTO.getId());
                    uploadFilesDTO.setIds(FormatUtils.commaToList_Integer(objDTO.getIsUpload()));
                    uploadFilesService.updateInfoByQuery(uploadFilesDTO);
                }
                //endregion

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = newsService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //region 更新文件上传表中的recordId
                if (StringUtils.isNotBlank(objDTO.getIsUpload())) {
                    //1.先stopFlag=1
                    TransportUploadFilesDTOQuery uploadFilesDTO = new TransportUploadFilesDTOQuery();
                    uploadFilesDTO.setStopFlag(1);
                    uploadFilesDTO.setW_tableId(71);
                    uploadFilesDTO.setW_recordId(objDTO.getId());
                    uploadFilesService.updateInfoByQuery(uploadFilesDTO);

                    //2.再stopFlag=0
                    uploadFilesDTO = new TransportUploadFilesDTOQuery();
                    uploadFilesDTO.setStopFlag(0);
                    uploadFilesDTO.setIds(FormatUtils.commaToList_Integer(objDTO.getIsUpload()));
                    uploadFilesService.updateInfoByQuery(uploadFilesDTO);
                }
                //endregion
            }

            //region *** 更新信息完毕记录操作日志 ***
            objDTO.setNewsContent("");  //文章内容太长，占用空间，不保存。
            logService.insertSimple(1, 71, objDTO.getId(), 2,
                    "更新文章信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return string
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            //处理加密（加密文件只能本人删除）
            TransportNewsDTO obj = newsService.getById(id);
            if (obj.getIsSecret() == 1 && !Objects.equals(obj.getAdminId(), curr_obj.getId())) {
                map = OperateCode.CompositionResult(map, -10, "你没有权限删除此记录！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            Boolean isNext = newsService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 71, id, 4,
                    "删除文章信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return string
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = newsService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 71, id == null ? 0 : id, 2,
                    "更新文章状态",
                    "记录状态更新" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

}